package be.rubengerits.bluetooth.tester.bluetooth;

import android.bluetooth.*;
import java.io.*;
import java.util.*;
import android.widget.*;

public class BluetoothConnection extends Thread {
	private BluetoothSocket mmSocket;
    private BluetoothDevice mmDevice;
	private BluetoothAdapter mmAdapter;
	private BluetoothHandler mmHandler;

	private static BluetoothConnection instance;
	
	public static BluetoothConnection getInstance(BluetoothHandler handler, BluetoothDevice device, BluetoothAdapter adapter) {
		if (instance == null)
			instance = new BluetoothConnection(handler, device, adapter);
		
		return instance;
	}
	
    private BluetoothConnection(BluetoothHandler handler, BluetoothDevice device, BluetoothAdapter adapter) {
        BluetoothSocket tmp = null;
		mmHandler = handler;
        mmDevice = device;
		mmAdapter = adapter;

        try {
            tmp = device.createRfcommSocketToServiceRecord(UUID.fromString("test"));
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        mmAdapter.cancelDiscovery();

        try {
        	mmSocket.connect();
        } catch (IOException connectException) {
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

		while (true) {
			try {
				mmHandler.read(mmSocket);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
    }

	public void send(Class<BluetoothHandler> handlerClass, Object o) throws BluetoothException {
		BluetoothHandler handler = null;
		try {
			handler = handlerClass.newInstance();
		} catch (Exception e) {
			throw new BluetoothException(e);
		}
		try {
			handler.write(o);
		} catch (IOException e) {}
	}

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
